package com.douwong.student.activity;

import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.douwong.student.R;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.BaseActivity;
import com.douwong.student.contant.Config;
import com.douwong.student.model.StatusCode;
import com.douwong.student.model.UserBean;
import com.douwong.student.rxjava.NetWork;
import com.douwong.student.utils.CyptoUtils;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.PreferencesUtils;
import com.douwong.student.utils.ToastUtils;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * @autor yichao
 * @time 2017/3/2217:41
 * @des 登录
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "LoginActivity";
    private LinearLayout mLogin_ll;
    private EditText mEtextUserName, mEtextPassword;
    private ImageView mAccount_delete_img, mPwd_delete_img;
    private Button mButtonLogin;
    private RelativeLayout mRootView;
    private PreferencesUtils mInstance;



    @Override
    protected void initView() {
        setContentView(R.layout.login_layout);
        mRootView = (RelativeLayout) findViewById(R.id.login_rl);
        mLogin_ll = (LinearLayout) findViewById(R.id.login_ll);
        mEtextUserName = (EditText) findViewById(R.id.account_edit);
        mEtextPassword = (EditText) findViewById(R.id.pwd_edit);
        mAccount_delete_img = (ImageView) findViewById(R.id.account_delete_img);
        mPwd_delete_img = (ImageView) findViewById(R.id.pwd_delete_img);
        mButtonLogin = (Button) findViewById(R.id.login_text);
    }

    @Override
    protected void initData() {
        mInstance = PreferencesUtils.getInstance();
        String user_name = mInstance.getString(Config.USER_NAME, "");
        String pwd = mInstance.getString(Config.PASS_WORD, "");
        if (!user_name.equals("")) {
            mEtextUserName.setText(user_name);
            mAccount_delete_img.setVisibility(View.VISIBLE);
        }
        if (!pwd.equals("")) {
            mEtextPassword.setText(pwd);
            mPwd_delete_img.setVisibility(View.VISIBLE);
        }
        mEtextUserName.addTextChangedListener(new TextChangeListener(mEtextUserName, mAccount_delete_img));
        mEtextPassword.addTextChangedListener(new TextChangeListener(mEtextPassword, mPwd_delete_img));
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mAccount_delete_img.setOnClickListener(this);
        mPwd_delete_img.setOnClickListener(this);
        mButtonLogin.setOnClickListener(this);
        mRootView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_rl:
                finish();
                break;
            case R.id.account_delete_img:
                mEtextUserName.setText("");
                mAccount_delete_img.setVisibility(View.INVISIBLE);
                break;
            case R.id.pwd_delete_img:
                mEtextPassword.setText("");
                mPwd_delete_img.setVisibility(View.INVISIBLE);
                break;
            case R.id.login_text:
                final String userName = mEtextUserName.getText().toString().trim();
                final String password = mEtextPassword.getText().toString().trim();
                if (userName.equals("")) {
                    ToastUtils.makeText(this, "请输入账号");
                    return;
                }
                if (password.equals("")) {
                    ToastUtils.makeText(this, "请输入密码");
                    return;
                }
                //检测网络
                if (!NetUtils.NetwrokIsUseful(this)) {
                    ToastUtils.makeText(this, "请检查网络");
                    return;
                }
                unsubscribe();
                //登录
                subscription = NetWork.getEndPointInterface()
                        .login(userName, CyptoUtils.MD5(password), "131", NetUtils.getlocalip(this))
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mButtonLogin.setSelected(true);
                        mButtonLogin.setText("正在登录 ...");
                    }
                }).subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<StatusCode<UserBean>>() {
                    @Override
                    public void onCompleted() {
                        LogUtils.i(TAG, "登录完成");
                        setLoginState();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.i(TAG, "登录失败" + e.toString());
                        ToastUtils.makeText(LoginActivity.this, "登录失败");
                        setLoginState();
                    }

                    @Override
                    public void onNext(StatusCode<UserBean> userBeanStatusCode) {
                        LogUtils.i(TAG, "登录成功" + userBeanStatusCode.toString());
                        if (userBeanStatusCode.isFlag()) {
                            //登录成功
                            BaseApplication.isLogin=true;
                            BaseApplication.sUserBean=userBeanStatusCode.getData();
                            setResult(MainActivity.LoginResponeCode);
                            //保存账号密码
                            PreferencesUtils.getInstance().putString(Config.USER_NAME,userName);
                            PreferencesUtils.getInstance().putString(Config.PASS_WORD,password);
                            Intent intent=new Intent();
                            intent.setAction(Config.LOGIN_SUCCESS);
                            sendBroadcast(intent);
                            finish();
                        } else {
                            ToastUtils.makeText(LoginActivity.this, userBeanStatusCode.getDetailMsg());
                            setLoginState();
                        }


                    }
                });
                break;

        }

    }
    private void setLoginState(){
        mButtonLogin.setSelected(false);
        mButtonLogin.setText("登    录");
    }

    private class TextChangeListener implements TextWatcher {
        private EditText mEditText;
        private ImageView mImageView;

        private TextChangeListener(EditText editText, ImageView imageView) {
            this.mEditText = editText;
            this.mImageView = imageView;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (!mEditText.getText().toString().trim().equals("")) {
                mImageView.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }
}
